const express = require('express')
const path = require('path')
const fs = require('fs')
const fontmin = require('./fontmin')// 字体切割程序
const router = express.Router()
// 设置可用字体
const fonts = [
  {font: 'SourceHanSerifCN-Medium', name: '思源宋体'},
  {font: 'LiZiKaiti', name: '励字楷体'}
]

// 文件重命名
/*let rename = async () => {
	let pathName = path.join(__dirname, '../../public/files/font') // 定义路径变量
	let files = fs.readdirSync(pathName)
  // 遍历文件先获取每个文件的详情信息，再改名
  await files.forEach((file) => {
    let name = file.split('.')[0]
    let ext = file.split('.')[1]
    let newName = `${name}${Date.now().toString(32)+Math.floor(Math.random(10000)*10000)}`   
    // console.log(`${pathName}\\${name}.${ext}`)
    // console.log(`${pathName}\\${newName}.${ext}`)
    
    let oldPath = path.join(`${pathName}/${name}.${ext}`)
    let newPath = path.join(`${pathName}/${newName}.${ext}`)

    fs.renameSync(oldPath, newPath)
  })
}*/

/*
  字体优化接口
  req接受两个参数：font->要使用的字体文件名称，例如fonts常量中定义好的：SourceHanSerifCN-Medium
                  text->要合成的文本内容
*/
router.post('/fontmin', async (req, res) => {
  const {font, text} = req.body
  // 如果传递的font字体在后台没有就返回code:1
  const item = fonts.find(e => e.font === font)
  if(item) {
    fontmin(font, text, async (e) => {
      if(e === 'done') {
        // console.log('fontmin done')

        // 重命名文件
        //await rename()
        // console.log('rename done')

        /*let pathName = path.join(__dirname, '../../public/files/font')
        let files = fs.readdirSync(pathName)
        let curTtfName = ''
        
        // 取出重命名后的文件地址，准备发给前端
        await files.forEach((file) => {
          let name = file.split('.')[0]
          let ext = file.split('.')[1]
          if(ext === 'ttf'){
            curTtfName = name
          }
        })*/
        
        res.send({
          code: 0,
          url: '/files/font/' + font + '.ttf',
          font: font
        })
      } 
    })
  } else {
    res.send({
      code: 1,
      msg: '没有请求的字体文件'
    })
  }
})

module.exports = router